package com.wxyzz.canteencommon.exception;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.wxyzz.canteencommon.common.R;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * --- 加油，努力 ---
 *
 * @Author XYP
 * @Date 2024/10/6
 * @Solgne 从想做到能做
 * @Desc
 */
@RestControllerAdvice
public class MyGlobalExceptionHandler {
    @ExceptionHandler(BindException.class)
    public R handleBindException(BindException e) {
        String message = join(e.getAllErrors(),
                DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        return R.fail(message);
    }

    private <E> String join(Collection<E> collection, Function<E, String>
            function, CharSequence delimiter) {
        if (CollUtil.isEmpty(collection)) {
            return StrUtil.EMPTY;
        }
        return
                collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
    }



    @ExceptionHandler(CustmerException.class)
    public R handlerException (CustmerException e) {
        System.out.println("全局异常处理器正在捕获异常...");
        return R.fail(e.getCode(),e.getMsg());
    }

}
